package com.qing.request_params.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Enumeration;

@Component
public class HttpRequestInfoInterceptor implements HandlerInterceptor {

	Logger logger = LoggerFactory.getLogger(HttpRequestInfoInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.info("请求方式：{}", request.getMethod());
		logger.info("请求路径：{}", request.getRequestURI());
		if (request.getMethod().equalsIgnoreCase("post")) {
			StringBuilder sb = new StringBuilder();
			String line;
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			String body = sb.toString();
			logger.info("Body请求体:{}", body);
		} else {
			Enumeration<String> parameterNames = request.getParameterNames();
			while (parameterNames.hasMoreElements()) {
				String parameterName = parameterNames.nextElement();
				logger.info("请求参数{}:{}", parameterName, request.getParameter(parameterName));
			}
		}
		logger.info("请求状态：{}", response.getStatus());
		return true;
	}
}